/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */

package com.github.pig.auth.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.provider.token.ConsumerTokenServices;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.github.pig.common.constant.SecurityConstants;
import com.github.pig.common.util.R;

/**
 * @author lengleng
 * @date 2018年03月10日
 */
@RestController
@RequestMapping("/authentication")
public class AuthenticationController {
	@Autowired
	@Qualifier("consumerTokenServices")
	private ConsumerTokenServices consumerTokenServices;

	/**
	 * 认证页面
	 * 
	 * @return ModelAndView
	 */
	@GetMapping("/require")
	public ModelAndView require() {
		return new ModelAndView("ftl/login");
	}

	/**
	 * 用户信息校验
	 * 
	 * @param authentication
	 *            信息
	 * @return 用户信息
	 */
	@RequestMapping("/user")
	public Object user(Authentication authentication) {
		return authentication.getPrincipal();
	}

	/**
	 * 清除Redis中 accesstoken refreshtoken
	 *
	 * @param accesstoken
	 *            accesstoken
	 * @return true/false
	 */
	@PostMapping("/removeToken")
	@CacheEvict(value = SecurityConstants.TOKEN_USER_DETAIL, key = "#accesstoken")
	public R<Boolean> removeToken(String accesstoken) {
		return new R<>(consumerTokenServices.revokeToken(accesstoken));
	}
}